package com.example.http_handler_image;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.widget.ImageView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class ImageThread extends Thread {

    private String url;
    private ImageView imageView;
    private Handler handler;

    public ImageThread(String url, ImageView imageView, Handler handler){
        this.url = url;
        this.imageView = imageView;
        this.handler = handler;
    }

    HttpURLConnection conn = null;
    InputStream stream = null;
    @Override
    public void run() {

        try {
            URL httpUrl = new URL(url);

            try {
                conn = (HttpURLConnection) httpUrl.openConnection();
                conn.setRequestMethod("GET");
                conn.setReadTimeout(5000);

                stream = conn.getInputStream();

                FileOutputStream outputStream = null;
                String fileName = String.valueOf(System.currentTimeMillis()) ;
                File downloadFile = null;
                //将文件下载到SD卡，首先判断SD卡是否存在,存在之后创建文件即可
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    File parent = Environment.getExternalStorageDirectory();
                    downloadFile = new File(parent, fileName);
                    outputStream = new FileOutputStream(downloadFile);
                }
                //读取数据
                byte[] bytes = new byte[2*1024];
                int lens;
                if (outputStream != null) {
                    while ((lens = stream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, lens);
                    }
                }

                final Bitmap bitmap = BitmapFactory.decodeFile(downloadFile.getAbsolutePath());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //将百度源代码信息下载下来，在本地webview中展现出来，指定类型为content
                       imageView.setImageBitmap(bitmap);
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if ( stream != null){
                    try {
                        stream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (conn !=null){
                    conn.disconnect();
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }


    }
}
